﻿using Microsoft.Toolkit.Uwp.Notifications;
using Newtonsoft.Json;
using socketio.socketio;
using SocketioTest.Common;
using SocketioTest.ViewModel;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Runtime.Serialization;
using System.Threading.Tasks;
using System.Windows.Controls;
using static socketio.socketio.Data;

namespace SocketioTest.View
{
    /// <summary>
    /// ChatContent.xaml 的交互逻辑
    /// </summary>
    public partial class ChatContent : Page
    {
        private ObservableCollection<ChatRecord> _messageList;
        public ObservableCollection<ChatRecord>? MessageList
        {
            get
            {
                if (_messageList == null)
                {
                    _messageList = new ObservableCollection<ChatRecord>();
                }
                return _messageList;
            }
        }

        public ChatContent()
        {
            InitializeComponent();
            MessageListBox.ItemsSource = MessageList;
            //MessageList.Add(new ChatRecord() { sender_name = "A", msg = "欢迎 欢迎欢迎欢迎欢迎欢迎欢迎欢迎你他妈的用世界上最吊的聊天软件", sender_userId = 1, senderimg = "http://img.hfxinmu.cn/she.png" });
            //MessageListBox.ItemsSource = MessageList;
            Socketa.client.On("updateChatMessageList", response =>
            {
                object text = response.GetValue<object>();
                this.ReceivedUpdateChatEvent(text);
            });
        }

        public void MessageListDemo()
        {
            MessageList.Clear();
            for (int i = 0; i < Global.chatMessageList.Count; i++)
            {
                var sender_userId = Global.chatMessageList[i].sender_userId;
                var receiver_userId = Global.chatMessageList[i].receiver_userId;
                if (MainWindowViewModel.GetInstance().SelectdUsersChanged != null)
                {
                    Console.WriteLine(JsonConvert.SerializeObject(Global.chatMessageList));
                    if ((MainWindowViewModel.GetInstance().SelectdUsersChanged.userId == sender_userId && Global.uid == receiver_userId) || (MainWindowViewModel.GetInstance().SelectdUsersChanged.userId == receiver_userId && Global.uid == sender_userId))
                    {
                        MessageList.Add(new ChatRecord() { 
                            sender_name = Global.chatMessageList[i].sender_name,
                            sender_userId = Global.chatMessageList[i].sender_userId,
                            senderimg = Global.chatMessageList[i].senderimg,
                            msg = Global.chatMessageList[i].msg,
                            receiver_userId = Global.chatMessageList[i].receiver_userId,
                            receiver_userName = Global.chatMessageList[i].receiver_userName,
                            time = Global.chatMessageList[i].time
                        });
                    }
                }
            }
        }

        /**
         * 收到socket消息
         * */
        public void ReceivedUpdateChatEvent(object objjson)
        {
            var objjsons = objjson.ToString();
            ChatRecord msgstr = JsonConvert.DeserializeObject<ChatRecord>(objjsons);

            if (msgstr != null)
            {
                Global.chatMessageList.Add(msgstr);
                new ToastContentBuilder()
                .AddArgument("action", "viewConversation")
                .AddArgument("conversationId", 9813)
                .AddText(msgstr.sender_name+" 发来一条消息")
                .AddText(msgstr.msg)
                .Show();

                if (MainWindowViewModel.GetInstance().SelectdUsersChanged != null && MainWindowViewModel.GetInstance().SelectdUsersChanged.userId == msgstr.sender_userId)
                {
                    MessageListBox.Dispatcher.BeginInvoke(new Action(() =>
                    {
                        MessageList.Add(msgstr);
                    }));
                }
            }
        }

        private void SendTextMsgCommand(object sender, System.Windows.RoutedEventArgs e)
        {
            if (MainWindowViewModel.GetInstance().SelectdUsersChanged == null)
            {
                new ToastContentBuilder()
                .AddArgument("action", "viewConversation")
                .AddArgument("conversationId", 9813)
                .AddText("请选择联系人")
                .Show();
                return;
            }
            if (MsgInputText.Text == "" || MsgInputText.Text == null)
            {
                new ToastContentBuilder()
                .AddArgument("action", "viewConversation")
                .AddArgument("conversationId", 9813)
                .AddText("填写要发送的内容")
                .Show();
                return;
            }
            var msg = new ChatRecord()
            {
                sender_name = Global.name,
                sender_userId = Global.uid,
                senderimg = Global.avatar,
                msg = MsgInputText.Text,
                receiver_userId = MainWindowViewModel.GetInstance().SelectdUsersChanged.userId,
                receiver_userName = MainWindowViewModel.GetInstance().SelectdUsersChanged.name,
                time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:ffff")
            };
            MessageList.Add(msg);
            Global.chatMessageList.Add(msg);

            Socketa.SendMsg(msg);
            MsgInputText.Text = "";
        }
    }
}
